#region (c) 2014 THN Solutions LLC. - All rights reserved
/*
THN DATA ABSTRACTION LAYER version 1

Copyright (c) 2014, THN Solutions LLC. ( www.ThnSolutions.com )
Author: Nguyễn, M. Hải                 ( www.Minh-Hai.com     )
All rights reserved.

This library is dual-licensed.
  + For commercial software, please obtain a commercial license from THN Solutions LLC.

  + For free software, this library is licensed under GPL version 3. A summary of GPLv3 is
    listed below. You should also find a copy of GPLv3 as file License_GPLv3.txt included
	with the source-code files.

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License version 3 as published by
    the Free Software Foundation  of the License.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#endregion

#region Using directives
using System;
using System.Reflection;
using System.ComponentModel;
using Thn.Application;
using Thn.Collections;
#endregion

namespace Thn.Data
{
	/// <summary>
	/// Base class for all condition
	/// </summary>
	[Serializable]
    [TypeConverter(typeof(ConditionConverter))]
	public abstract class Condition
	{
		#region Static Constructors
		#region Equal
		/// <summary>
		/// Creates a new EQUAL condition (fieldName = value)
		/// </summary>
		public static SingleCondition Equal(string fieldName, IComparable value)
		{
			return new SingleCondition(fieldName, value, ComparisionType.Equal);
		}

		/// <summary>
		/// Creates a new EQUAL condition (fieldName = value)
		/// </summary>
		public static SingleCondition Equal(string fieldName, IComparable value, string errorMessage)
		{
			return new SingleCondition(fieldName, value, ComparisionType.Equal, errorMessage);
		}
		#endregion

        #region Not Equal
        /// <summary>
        /// Creates a new Not Equal condition (fieldName != value)
        /// </summary>
        public static SingleCondition NotEqual(string fieldName, IComparable value)
        {
            return new SingleCondition(fieldName, value, ComparisionType.NotEqual);
        }

        /// <summary>
        /// Creates a new Not Equal condition (fieldName != value)
        /// </summary>
        public static SingleCondition NotEqual(string fieldName, IComparable value, string errorMessage)
        {
            return new SingleCondition(fieldName, value, ComparisionType.NotEqual, errorMessage);
        }
        #endregion

		#region Greater, Greater or equal
		/// <summary>
		/// Creates a new GREATER condition (fieldName > value)
		/// </summary>
		public static SingleCondition Greater(string fieldName, IComparable value)
		{
			return new SingleCondition(fieldName, value, ComparisionType.Greater);
		}

		/// <summary>
		/// Creates a new GREATER condition (fieldName > value)
		/// </summary>
		public static SingleCondition Greater(string fieldName, IComparable value, string errorMessage)
		{
			return new SingleCondition(fieldName, value, ComparisionType.Greater, errorMessage);
		}

		/// <summary>
		/// Creates a new GreaterOrEqual condition (fieldName >= value)
		/// </summary>
		public static SingleCondition GreaterOrEqual(string fieldName, IComparable value)
		{
			return new SingleCondition(fieldName, value, ComparisionType.GreaterOrEqual);
		}

		/// <summary>
		/// Creates a new GreaterOrEqual condition (fieldName >= value)
		/// </summary>
		public static SingleCondition GreaterOrEqual(string fieldName, IComparable value, string errorMessage)
		{
			return new SingleCondition(fieldName, value, ComparisionType.GreaterOrEqual, errorMessage);
		}
		#endregion

		#region Less, Less or equal
		/// <summary>
		/// Creates a new LESS condition (fieldName less than value)
		/// </summary>
		public static SingleCondition Less(string fieldName, IComparable value)
		{
			return new SingleCondition(fieldName, value, ComparisionType.Less);
		}

		/// <summary>
		/// Creates a new LESS condition (fieldName less than value)
		/// </summary>
		public static SingleCondition Less(string fieldName, IComparable value, string errorMessage)
		{
			return new SingleCondition(fieldName, value, ComparisionType.Less, errorMessage);
		}

		/// <summary>
		/// Creates a new LessOrEqual condition (fieldName less or equal value)
		/// </summary>
		public static SingleCondition LessOrEqual(string fieldName, IComparable value)
		{
			return new SingleCondition(fieldName, value, ComparisionType.LessOrEqual);
		}

		/// <summary>
		/// Creates a new LessOrEqual condition (fieldName less or equal value)
		/// </summary>
		public static SingleCondition LessOrEqual(string fieldName, IComparable value, string errorMessage)
		{
			return new SingleCondition(fieldName, value, ComparisionType.LessOrEqual, errorMessage);
		}
		#endregion

		#region Not
        /// <summary>
        /// Creates a new Not condition (!inner)
        /// </summary>
        public static NotCondition Not(Condition inner)
        {
            return new NotCondition(inner);
        }
		#endregion

		#region Unique
		/// <summary>
		/// Creates a new Unique condition (fieldName's value must be non-repeating in a collection or model)
		/// </summary>
		public static SingleCondition Unique(string fieldName)
		{
			return new SingleCondition(fieldName, null, ComparisionType.Unique);
		}

		/// <summary>
		/// Creates a new Unique condition (fieldName's value must be non-repeating in a collection or model)
		/// </summary>
		public static SingleCondition Unique(string fieldName, string errorMessage)
		{
			return new SingleCondition(fieldName, null, ComparisionType.Unique, errorMessage);
		}
		#endregion

		#region Not Empty
		/// <summary>
		/// Creates a new Unique condition (fieldName's value must not be null or empty)
		/// </summary>
		public static SingleCondition NotEmpty(string fieldName)
		{
			return new SingleCondition(fieldName, null, ComparisionType.NotEmpty);
		}

		/// <summary>
		/// Creates a new Unique condition (fieldName's value must not be null or empty)
		/// </summary>
		public static SingleCondition NotEmpty(string fieldName, string errorMessage)
		{
			return new SingleCondition(fieldName, null, ComparisionType.NotEmpty, errorMessage);
		}
		#endregion
		#endregion

		#region Empty
		static Condition mEmpty;
		static object SyncLock = new object();
		/// <summary>
		/// Gets the empty instance
		/// </summary>
		public static Condition Empty
		{
			get
			{
				if (mEmpty == null)
				{
					Condition tmp = new EmptyCondition();

					lock (SyncLock)
					{
						mEmpty = tmp;
					}
				}

				return mEmpty;
			}
		}
		#endregion

		#region Equals
		/// <summary>
		/// Compare this instance against another
		/// </summary>
		public override bool Equals(object obj)
		{
			bool equal = false;

			if (obj != null)
			{
				if (this is SingleCondition)
				{
					equal = ((SingleCondition)this).Equals(obj);
				}
				else if (this is NestedCondition)
				{
					equal = ((NestedCondition)this).Equals(obj);
				}
			}

			return equal;
		}

        /// <summary>
        /// Gets ID of this object
        /// </summary>
        public override int GetHashCode()
        {
            return base.GetHashCode();
        }
		#endregion

		#region Match
		/// <summary>
		/// Evaluate a data object against condition requirement(s).
		/// Returns true if matching
		/// </summary>
		public static bool Match(object data, Condition condition)
		{
			return IsMatch(data.GetType(), data, condition, null);
		}

		/// <summary>
		/// Evaluate a data object against condition requirement(s).
		/// Returns true if matching
		/// </summary>
		/// <param name="condition">Condition to evaluate</param>
		/// <param name="data">object to evaluate</param>
		/// <param name="errors">If not null, failed conditions will be added to this errors after evaluation</param>
		public static bool Match(object data, Condition condition, ConditionCollection errors)
		{
			return IsMatch(data.GetType(), data, condition, errors);
		}

		/// <summary>
		/// Evaluate a data object against condition requirement(s).
		/// Returns true if matching.
		/// Note: passing a DataType will reduce slight overhead for GetType()
		/// </summary>
		public static bool Match(Type DataType, object data, Condition condition)
		{
			return IsMatch(DataType, data, condition, null);
		}

		/// <summary>
		/// Evaluate a data object against condition requirement(s).
		/// Returns true if matching.
		/// Note: passing a DataType will reduce slight overhead for GetType()
		/// </summary>
		/// <param name="condition">Condition to evaluate</param>
		/// <param name="data">object to evaluate</param>
		/// <param name="DataType">type of object (so that I don't have to reflect)</param>
		/// <param name="errors">If not null, failed conditions will be added to this errors after evaluation</param>
		public static bool Match(Type DataType, object data, Condition condition, ConditionCollection errors)
		{
			return IsMatch(DataType, data, condition, null);
		}
		#endregion

		#region IsMatch
		/// <summary>
		/// Evaluate data against a condition
		/// </summary>
		/// <param name="dataType">passing a DataType will reduce slight overhead for GetType()</param>
		/// <param name="data">object to compare</param>
		/// <param name="condition">condition root</param>
		/// <param name="errors">if passed, add non-matching condition to errors as result</param>
		static bool IsMatch(Type dataType, object data, Condition condition, ConditionCollection errors)
		{
			bool result = false;
            if (condition is NotCondition)
            {
                NotCondition notCon = (NotCondition)condition;
                result = !IsMatch(dataType, data, notCon.Inner, errors);
            }
            else if (condition is NestedCondition)
            {
                NestedCondition nc = (NestedCondition)condition;
                if (nc.Combination == CombinationType.And)
                    result = IsMatch(dataType, data, nc.Left, errors) && IsMatch(dataType, data, nc.Right, errors);
                else
                    result = IsMatch(dataType, data, nc.Left, errors) || IsMatch(dataType, data, nc.Right, errors);
            }
            else
            {//single condition
                SingleCondition sc = (SingleCondition)condition;

                MemberInfo[] mi = dataType.GetMember(sc.Field, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
                if ((mi != null) && (mi.Length > 0))
                {
                    object value = null;
                    if (mi[0] is FieldInfo) value = ((FieldInfo)mi[0]).GetValue(data);
                    else if (mi[0] is PropertyInfo) value = ((PropertyInfo)mi[0]).GetValue(data, null);

                    if (value != null)
                    {
                        IComparable comparable = (IComparable)value;
                        try
                        {
                            switch (sc.Operation)
                            {
                                case ComparisionType.Equal:
                                    result = comparable.CompareTo(sc.Value) == 0;
                                    break;
                                case ComparisionType.Greater:
                                    result = comparable.CompareTo(sc.Value) > 0;
                                    break;
                                case ComparisionType.GreaterOrEqual:
                                    result = comparable.CompareTo(sc.Value) >= 0;
                                    break;
                                case ComparisionType.Less:
                                    result = comparable.CompareTo(sc.Value) < 0;
                                    break;
                                case ComparisionType.LessOrEqual:
                                    result = comparable.CompareTo(sc.Value) <= 0;
                                    break;
                                case ComparisionType.NotEqual:
                                    result = comparable.CompareTo(sc.Value) != 0;
                                    break;
                                case ComparisionType.NotEmpty:
                                    result = !Nulls.IsNullOrEmpty(value);
                                    break;
                            }//switch
                        }
                        catch { }
                    }
                }//mi!=null

                //failed
                if (!result)
                {
                    if (errors != null) errors.Add(condition);
                }
            }//single condition

			return result;
		}
		#endregion

		#region Operators overload
		/// <summary>
		/// Combine two conditions by AND operation
		/// </summary>
		public static Condition operator &(Condition c1, Condition c2)
		{
			if (c1 == null) return c2;
			else if (c2 == null) return c1;
			else return new NestedCondition(c1, c2, CombinationType.And);
		}

		/// <summary>
		/// Combine two conditions by OR operation
		/// </summary>
		public static Condition operator |(Condition c1, Condition c2)
		{
			if (c1 == null) return c2;
			else if (c2 == null) return c1;
			else return new NestedCondition(c1, c2, CombinationType.Or);        
        }

        /// <summary>
        /// Create an opposite of condition
        /// </summary>
        public static Condition operator !(Condition c1)
        {
            return new NotCondition(c1);
        }
		#endregion
	}
}
